import VueRouter from 'vue-router'
import store from 'store'
import { getCookie } from 'utils/authService'
import NProgress from 'nprogress'
import LoginService from "api/login"
import Ajax from 'api/customajax'
import Cas from 'api/cas'
import * as types from 'store/modules/login'
import 'nprogress/nprogress.css'

const Login = resolve => require(['../views/login'], resolve)
const Home = resolve => require(['../views/layout/home.vue'], resolve)
const Outpage = resolve => require(['../views/layout/home.vue'], resolve)

const MonitorTemplate = resolve => require(['../views/config/monitortemplate.vue'], resolve)
const User = resolve => require(['../views/security/user.vue'], resolve)
const Menu = resolve => require(['../views/security/menu.vue'], resolve)
const Role = resolve => require(['../views/security/role.vue'], resolve)
const Log = resolve => require(['../views/config/logmanager'], resolve)

// Topo
const GraphShower = resolve => require(['../views/graph/shower.vue'], resolve)
const DeviceMgm = resolve => require(['../views/device/deviceMgm.vue'], resolve)
const TopoMgm = resolve => require(['../views/topo/index.vue'], resolve)
const TopoConfig = resolve => require(['../views/topo/topoConfig.vue'], resolve)
const IconMgm = resolve => require(['../views/config/iconmanager.vue'], resolve)
const subnetMgm = resolve => require(['../views/topo/subnetMgm.vue'], resolve)

// report
const AlarmInfo = resolve => require(['../views/alarm/info.vue'], resolve)
const AlarmMgm = resolve => require(['../views/alarm/manage.vue'], resolve)
const AlarmHandle = resolve => require(['../views/alarm/handle.vue'], resolve)
const Report = resolve => require(['../views/report/reportMgm.vue'], resolve)

//graph
const graphMgm = resolve => require(['../views/graph/graphMgm.vue'], resolve)
const dsMgm = resolve => require(['../views/graph/dsMgm.vue'], resolve)
const dashboard = resolve => require(['../views/graph/dashboard.vue'], resolve)
const devStatus = resolve => require(['../views/graph/devStatus.vue'], resolve)
const businessStatus = resolve => require(['../views/graph/businessStatus.vue'], resolve)
const zabbix = resolve => require(['../views/zabbix/normalConfig.vue'], resolve)

// bus
const BusTopo = resolve => require(['../views/bus/index.vue'], resolve)

// SCREEN 大屏展示
const BigScreen = resolve => require(['../views/screen/bigshower.vue'], resolve)

let routes = [{
        path: '/home',
        component: Home,
        // redirect: 'GraphShower',
        meta: {
            requireAuth: false,
        },
        children: [{
                name: "首页",
                path: '/',
                meta: {
                    key: 'new_home',
                    requireAuth: false,
                },
                component: GraphShower
            },
            {
                path: '/system/user',
                name: "用户管理",
                meta: {
                    requireAuth: false,
                },
                component: User
            },
            {
                path: '/system/role',
                name: "权限管理",
                meta: {
                    requireAuth: false,
                },
                component: Role
            },
            {
                name: '菜单管理',
                path: '/system/menu',
                meta: {
                    requireAuth: false,
                },
                component: Menu
            },

            {
                name: '设备管理',
                path: '/device/deviceMgm',
                meta: {
                    requireAuth: false,
                },
                component: DeviceMgm
            },
            {
                name: "告警信息查询",
                path: '/alarm/info',
                meta: {
                    requireAuth: false,
                },
                component: AlarmInfo
            },
            {
                name: "告警设置",
                path: '/alarm/manage',
                meta: {
                    requireAuth: false,
                },
                component: AlarmMgm
            },
            {
                name: "告警处理",
                path: '/alarm/handle',
                meta: {
                    requireAuth: false,
                },
                component: AlarmHandle
            },
            {
                name: "图标管理",
                path: '/manager/iconmanager',
                meta: {
                    requireAuth: false,
                },
                component: IconMgm
            },
            {
                name: "日志管理",
                path: '/manager/logmanager',
                meta: {
                    requireAuth: false,
                },
                component: Log
            },
            {
                name: "模板管理",
                path: '/manager/monitortemplate',
                meta: {
                    requireAuth: false,
                },
                component: MonitorTemplate
            },
            {
                name: "拓扑管理",
                path: '/topo/topoMgm',
                meta: {
                    requireAuth: false,
                },
                component: TopoMgm
            },
            {
                name: "拓扑图配置",
                path: '/topo/config',
                meta: {
                    requireAuth: false,
                },
                component: TopoConfig
            },
            {
                name: "拓扑图列表",
                path: '/topo/graph/list',
                meta: {
                    requireAuth: false,
                },
                component: TopoConfig
            },
            {
                name: "子网管理",
                path: '/topo/subnetMgm',
                meta: {
                    requireAuth: false,
                },
                component: subnetMgm
            },
            {
                name: "业务拓扑",
                path: '/bus/topo',
                meta: {
                    requireAuth: false,
                },
                component: BusTopo
            },
            {
                name: "图形配置",
                path: "/graph/graphMgm",
                meta: {
                    requireAuth: false,
                },
                component: graphMgm,
            },
            {
                name: "数据配置",
                path: "/graph/dsMgm",
                meta: {
                    requireAuth: false,
                },
                component: dsMgm,
            },
            {
                name: "ReportMgm",
                path: "/report/reportMgm",
                meta: {
                    requireAuth: false,
                },
                component: Report,
            },
            {
                name: "自定义图形",
                path: "/graph/dashboard",
                meta: {
                    requireAuth: false,
                },
                component: dashboard,
            },
            {
                name: "自定义设备",
                path: "/graph/devStatus",
                meta: {
                    requireAuth: false,
                },
                component: devStatus,
            },
            {
                name: "自定义业务",
                path: "/bus/businessStatus",
                meta: {
                    requireAuth: false,
                },
                component: businessStatus,
            },
            {
                name: "监控配置",
                path: "/watch/manage",
                meta: {
                    displayName: 'zabbix',
                    requireAuth: false,
                },
                component: zabbix,
            },

        ]
    },
    {
        name: 'Login',
        path: '/login',
        component: Login
    },
    {
        name: "BigScreen",
        displayName: '大屏展示',
        path: "/screen/shower",
        meta: {
            requireAuth: false,
        },
        component: BigScreen
    },
    {
        path: '*',
        redirect: '/home'
    }
];

const router = new VueRouter({
    // mode: 'history',
    base: '/dirms',
    routes
});

function getUrlParam(path, name) {
    //取得整个地址栏
    var num = path.indexOf("?")
    path = path.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
    var arr = path.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            let key = arr[i].substring(0, num);
            console.log('key:' + key)
            if (key == name) {
                return arr[i].substr(num + 1)
            }
        }
    }
    return ''
}
//todo 最主要的目的是 验证token ，若果木有token 跳转到login 登陆页面
//我们这可以 增加一个加载的浮层 ，在每次跳转路由时 加载浮层，
//由跳转结束关闭浮层路
//在路由切换开始时调用
router.beforeEach((to, from, next) => {
    NProgress.start();
    // console.log('全局store');
    // console.log(store);
    // console.log('从哪来');
    // console.log(from);
    // console.log('到哪去');
    // console.log(to);
    // 验证 是否已经登录
    if (to.name == 'Login') {
        next()
        return
    }
    store.commit(types.GET_USER);
    let user = store.state.login.user
    let token = decodeURI(getUrlParam(to.fullPath, 'token'));
    if (!from.name && token) { //如果从根路径进入 并且 有token 进行本地验证和登录
        // console.log('token:' + token)
        Cas.localLogin(token).then(function(isLogin) {
            if (isLogin) {
                // console.log('Cas.localLogin(token):next')
                next();
            } else {
                // console.log('//登录失败 重新登录:')
                Cas.login();
            }
        }).catch(function(error) {
            // console.error('//登录失败 重新登录:')
            // console.error(error)
            Cas.login();
        });
    } else {
        // console.log('user:')
        // console.log(user)
        let toLogin = false;
        if (!user) { //未登录
            // console.log('!user: Cas.login()')
            toLogin = true;
        } else {
            // 此为同步查询方法
            LoginService.isLogin(function(data) {
                if (!data.isLogin) { //未登录
                    toLogin = true;
                }
            });
        }
        if (toLogin) {
            // console.log('user: LoginService.isLogin():toLogin')
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath
                } // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        } else {
            // console.log('user: LoginService.isLogin():next')
            next();
        }
    }

    // if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    //     // if (store.state.login.token) { // 通过vuex state获取当前的token是否存在
    //     if (getCookie('token')) {
    //         next();
    //     } else {
    //         next({
    //             path: '/login',
    //             query: {
    //                 redirect: to.fullPath
    //             } // 将跳转的路由path作为参数，登录成功后跳转到该路由
    //         })
    //     }
    // } else {
    //     next();
    // }
});
//在每次路由切换成功进入激活阶段时被调用
router.afterEach(() => {
    $('.container .main  .content-container').css({
        'overflow': 'auto',
        'overflow-y': 'auto'
    });
    NProgress.done();
});

export default router;